package com.hyl.crmclient.controller;

import com.hyl.crmclient.common.BaseCode;
import com.hyl.crmclient.service.RightService;
import com.hyl.crmclient.service.UserService;
import com.hyl.jpademo.entity.Right;
import com.hyl.jpademo.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * @Description TODO
 * @Author hyl
 * @Date 2022/6/5 19:53
 **/
@Controller
public class UserController {

	@Resource
	private UserService userService;

	@Resource
	private RightService rightService;

	//默认
	@RequestMapping(value = "/")
	public String defaultlogin(){
		return "login";
	}

	@RequestMapping(value = "/login")
	public String login(){
		return "login";
	}

	//登入
	@RequestMapping(value = "/dologin")
	public String dologin(String usrName, String usrPassword, HttpSession session){
		System.out.println(usrName+" "+usrPassword);
//		User loginUser = userService.login(usrName, usrPassword);
//		if(loginUser == null) {
//			return "login";
//		}
//		session.setAttribute(BaseCode.LOGIN_USER, loginUser);
//		return "index";
		//认证
//		String salt="czkt";
//		Md5Hash md5Hash = new Md5Hash(usrPassword, salt,2);
//		usrPassword = md5Hash.toString();

		UsernamePasswordToken token = new UsernamePasswordToken(usrName,usrPassword);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token); //认证
			User loginUser = (User) subject.getPrincipal();//身份
			Integer roleid = loginUser.getRole().getRoleId();
			loginUser.getRole().getRights().addAll(rightService.findByRoleid(roleid)); //权限==》访问控制
			//权限
			session.setAttribute(BaseCode.LOGIN_USER, loginUser);
			return "index";
		}catch (Exception e){
			e.printStackTrace();
			return "login";
		}
	}

	//退出
	@GetMapping(value = "/logout")
	public String logout(HttpSession session){
		session.removeAttribute(BaseCode.LOGIN_USER);
		return "login";
	}


	//进入首页
	@RequestMapping(value = "/index")
	public String toindex(){
		return "index";
	}


	//进入首页
	@RequestMapping(value = "/403")
	public String noauth(){
		return "403";
	}

}
